package com.tubeonfire.controller.admin;

import java.io.IOException;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.tubeonfire.model.admin.PlaylistModel;
import com.tubeonfire.service.YoutubeService;

@SuppressWarnings("serial")
public class YoutubeSearchServlet extends HttpServlet {

	private static final Logger log = Logger
			.getLogger(YoutubeSearchServlet.class.getName());

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		PlaylistModel plModel = new PlaylistModel();
		plModel.prepareAll(true);
		if (plModel.getListResult().size() > 0) {
			req.setAttribute("plModel", plModel);
			process(req, resp);
		} else {
			HttpSession session = req.getSession();
			session.setAttribute("alert",
					"You must create at least 1 playlist to search and add video from Youtube !");
			resp.sendRedirect("/admin/playlist/add");
		}
	}

	private void process(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			int page = 1;
			String type = (String) req.getParameter("type");
			String quanlity = (String) req.getParameter("quanlity");
			String keyword = (String) req.getParameter("keyword");
			try {
				page = Integer.parseInt(req.getParameter("page"));
			} catch (Exception e) {
				page = 1;
			}
			if (type != null && quanlity != null && keyword != null
					&& keyword.length() > 0) {
				YoutubeService tubeService = new YoutubeService();
				if (type.equals("1")) {
					tubeService.setPage(page);
					if (keyword.contains("http://www.youtube.com/user/")) {
						/*
						 * example : http://www.youtube.com/user/xuanhung2401
						 */
						String pattern = "(?:\\/user\\/)([\\w-]+)";
						Pattern compiledPattern = Pattern.compile(pattern);
						Matcher matcher = compiledPattern.matcher(keyword);
						if (matcher.find()) {
							keyword = matcher.group().replace("/user/", "");
						}
					} else if (keyword.contains("http://www.youtube.com")) {
						/*
						 * example : http://www.youtube.com/xuanhung2401
						 */
						String pattern = "(?:youtube.com\\/)([\\w-]+)";
						Pattern compiledPattern = Pattern.compile(pattern);
						Matcher matcher = compiledPattern.matcher(keyword);
						if (matcher.find()) {
							keyword = matcher.group().replace("youtube.com/",
									"");
						}
					}
					tubeService.searchByChannel(keyword, true);
				} else if (type.equals("2")) {
					tubeService.setPage(page);
					tubeService.searchByKey(keyword, quanlity.equals("2"));
				} else if (type.equals("3")) {
					String pattern = "(?:videos\\/|v=)([\\w-]+)";
					Pattern compiledPattern = Pattern.compile(pattern);
					Matcher matcher = compiledPattern.matcher(keyword);
					if (matcher.find()) {
						String fullStrId = matcher.group();
						fullStrId = (fullStrId.substring(
								fullStrId.length() - 11, fullStrId.length()));
						tubeService.searchById(fullStrId);
					}
				}
				resp.setCharacterEncoding("UTF-8");
				req.setAttribute("url", "/admin/youtube/search" + "?type=" + type
						+ "&quanlity=" + quanlity + "&keyword=" + keyword
						+ "&page=" + page);
				req.setAttribute("type", type);
				req.setAttribute("quanlity", quanlity);
				req.setAttribute("keyword", keyword);
				req.setAttribute("result", tubeService);
				req.getRequestDispatcher("/admin/youtube_search.jsp").forward(
						req, resp);
			} else {
				req.getRequestDispatcher("/admin/youtube_search.jsp").forward(
						req, resp);
			}
		} catch (Exception e) {
			log.warning(e.toString());
			e.printStackTrace();
			resp.sendError(4004,
					"We are sorry for the inconvenience ! Please try again later !");
		}
	}

	public static void main(String[] args) {
		String keyword = "http://www.youtube.com/xuanhung2401";
		String pattern = "(?:youtube.com\\/)([\\w-]+)";
		Pattern compiledPattern = Pattern.compile(pattern);
		Matcher matcher = compiledPattern.matcher(keyword);
		if (matcher.find()) {
			keyword = matcher.group().replace("youtube.com/", "");
			System.out.println(keyword);
		} else {
			System.out.println("has no");
		}
	}
}
